﻿namespace Manhua3.Helper
{
    using System;
    using System.Collections.Generic;
    using Windows.Networking.Connectivity;

    public enum NetworkState
    {
        /// <summary>
        /// 无法访问网络
        /// </summary>
        None,

        /// <summary>
        /// 能够访问网络, 但应该采取保守的方式访问
        /// </summary>
        Fixed,

        /// <summary>
        /// 能够没有任何限制的访问网络
        /// </summary>
        Unlimited,
    }

    public static class NetworkHelper
    {
        private static Dictionary<object, Action<NetworkState>> Callbacks = new Dictionary<object, Action<NetworkState>>();

        public static void StartListenNetworkStatusChanged()
        {
            NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;
        }

        public static void StopListenNetworkStatusChanged()
        {
            NetworkInformation.NetworkStatusChanged -= NetworkInformation_NetworkStatusChanged;
        }

        public static NetworkState GetNetworkState()
        {
            NetworkState state = NetworkState.None;
            var profile = NetworkInformation.GetInternetConnectionProfile();
            if (profile != null)
            {
                if (profile.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.None)
                {
                    var cost = profile.GetConnectionCost();
                    if (cost.NetworkCostType == NetworkCostType.Unrestricted ||
                        cost.NetworkCostType == NetworkCostType.Unknown)
                    {
                        state = NetworkState.Unlimited;
                    }
                    else
                    {
                        state = NetworkState.Fixed;
                    }
                }
            }

            return state;
        }

        public static void OnCallback(object sender, Action<NetworkState> callback)
        {
            Callbacks[sender] = callback;
        }

        public static void UnbindCallback(object sender)
        {
            try
            {
                if (Callbacks.ContainsKey(sender))
                    Callbacks.Remove(sender);
            }
            catch 
            {
            }
        }


        private static void NetworkInformation_NetworkStatusChanged(object sender)
        {
            NetworkState state = GetNetworkState();
            foreach (var item in Callbacks)
            {
                item.Value(state);
            }
        }
    }
}
